package com.zhaolin.contorller;

import com.zhaolin.entity.*;
import com.zhaolin.service.QuestionService;
import com.zhaolin.service.SurveyService;
import com.zhaolin.utils.MapControl;
import com.zhaolin.utils.SessionUtils;
import com.zhaolin.utils.SystemInit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.*;

@Controller
@RequestMapping("/survey")
@CrossOrigin
public class SurveyController {

    @Autowired
   SurveyService surveyService;

    @Autowired
    QuestionService questionService;

    @GetMapping("/query")
    public String query(){
        return "page/survey/list";
    }
    @PostMapping("/query")
    @ResponseBody
    public Map<String, Object> query(@RequestBody Survey survey, ModelMap modelMap){
        List<Survey> query = surveyService.query(survey);
        //创建者信息写入survey对象
        for (Survey entity : query ) {
            entity.setAdmin(SystemInit.adminMap.get(entity.getCreator()));
        }
        int count = surveyService.count(survey);
        System.out.println("出现的值"+query);
        return MapControl.getInstance().page(query,count).getMap();
    }

    @GetMapping("create")
    public String create(){
        return "page/survey/add";
    }

    @PostMapping("create_s")
    @ResponseBody
    public Map<String,Object> create(@RequestBody Survey survey, HttpServletRequest request){
        Admin currAdmin = SessionUtils.getAdmin(request);
        survey.setCreator(currAdmin.getId());
        survey.setAnon(survey.getAnon()!=null?0:1);
        survey.setState(Survey.state_create);
        int result = surveyService.create(survey);
        if (result<=0){
            //失败的情况下
            return  MapControl.getInstance().error().getMap();
        }
        return MapControl.getInstance().success().getMap();

    }

    @GetMapping("detail")
    public String detail(Integer id,ModelMap modelMap){
        Survey detail = surveyService.detail(id);
        modelMap.addAttribute("survey",detail);
        return "page/survey/update";
    }

    @PostMapping("update")
    @ResponseBody
    public Map<String, Object> update(@RequestBody Survey survey){
        survey.setAnon(survey.getAnon()!=null?0:1);
        int update = surveyService.update(survey);
        if (update>0){
            return MapControl.getInstance().success().getMap();
        }else{
            return MapControl.getInstance().error().getMap();
        }
    }

    @PostMapping("delete")
    @ResponseBody
    public Map<String,Object> delete(@RequestBody String id){
        System.out.println(id);
        int delete = surveyService.delete(id);
        if (delete>0){
            return MapControl.getInstance().success().getMap();
        }else{
            return MapControl.getInstance().error().getMap();
        }

    }

    @GetMapping("question")
    public String question(Integer id ,ModelMap modelMap ){
        Survey detail = surveyService.detail(id);
        modelMap.addAttribute("survey",detail);
        return "page/survey/question";
    }

    //浏览问卷
    @GetMapping("/preview/{id}")
    public String preview(@PathVariable Integer id,ModelMap modelMap){
        //先把问卷的明细查出来
        Survey detail = surveyService.detail(id);
        //查询问卷的问题
        Question question = new Question();
        question.setSurveyId(detail.getId());
        List<Question> query = questionService.query(question);
        //再讲查出来的题目装到
        detail.setQuestions(query);
        modelMap.addAttribute("survey",detail);
        return "page/survey/preview";
    }

    @RequestMapping(value = "/upload",method = RequestMethod.POST)
    public String upload(Integer id,@RequestParam("file") MultipartFile multipartFile,HttpServletRequest request){
        //上传的位置
        String path = request.getSession().getServletContext().getRealPath("/upload/");
        //判断该路径是否存在
        File file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        }
        //上传文件项
        String filename = multipartFile.getOriginalFilename();
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String saveName = uuid + "_" + filename.substring(filename.lastIndexOf(File.separator) + 1);
        try {
            multipartFile.transferTo(new File(path, saveName));
            Survey survey = new Survey();
            survey.setId(id);
            survey.setBgimg(saveName);
            surveyService.update(survey);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "redirect:preview/"+id;
    }

    @PostMapping("publish")
    @ResponseBody
    public  Map<String,Object>  publish(Integer id,ModelMap modelMap,HttpServletRequest request){
        Survey param = surveyService.detail(id);
        if (!Survey.state_exec.equals(param.getState())){
            return MapControl.getInstance().error("操作失败，当前问卷未在执行中！").getMap();
        }
        String uuid ="/diy/"+ UUID.randomUUID().toString();
        Survey survey = new Survey();
        survey.setId(id);
        String url="http://"+ request.getServerName() //服务地址
                +":"+ request.getServerPort()               //端口号
                +request.getContextPath()+uuid;         //项目名称
        survey.setUrl(url);
        surveyService.update(survey);
        return MapControl.getInstance().success().getMap();
    }

    @PostMapping("submit")
    @ResponseBody
    public Map<String,Object> submit(@RequestBody List<Map<String,Object>> list) {
        //创建一个集合装 选择题（单选和多选）
        List<AnswerOpt> listOpt = new ArrayList<>();
        //创建一个集合装 文本题（单文本和多文本）
        List<AnswerTxt> listTxt = new ArrayList<>();
        //把uuid弄出来
        String uuid = UUID.randomUUID().toString();
        //先循环 传进来的集合（集合内有还有个集合）
        for (Map<String,Object> num:list) {
            //把集合里的代表答案的集合弄出来
            List<Object> listOpts = (List<Object>) num.get("opts");
            //判断它是选择题还是文本题
            if (num.get("type").equals("1")||num.get("type").equals("2")){
                for (Object opts:listOpts){
                    AnswerOpt answerOpt = new AnswerOpt();
                    answerOpt.setQuestionId(ObjectInteger(num.get("questionId")));
                    answerOpt.setSurveyId(ObjectInteger(num.get("surveyId")));
                    answerOpt.setType(ObjectString(num.get("type")));
                    answerOpt.setOptId(ObjectInteger(opts));
                    answerOpt.setCreateTime(new Date());
                    answerOpt.setVoter(uuid);
                    listOpt.add(answerOpt);
                }
            }
            //判断是不是文本题目
            if (num.get("type").equals("3")||num.get("type").equals("4")){
                AnswerTxt answerTxt = new AnswerTxt();
                answerTxt.setQuestionId(ObjectInteger(num.get("questionId")));
                answerTxt.setSurveyId(ObjectInteger(num.get("surveyId")));
                answerTxt.setResult(ObjectString(num.get("result")));
                answerTxt.setCreateTime(new Date());
                answerTxt.setVoter(uuid);
                listTxt.add(answerTxt);
            }
        }
        Integer submit = surveyService.submit(listOpt, listTxt);
        return  MapControl.getInstance().success().getMap();
    }

    @GetMapping("query_detail/{id}")
    public String query_detail(@PathVariable("id") Integer id ,ModelMap modelMap){
        Survey survey = surveyService.detail(id);
        Question question = new Question();
        question.setSurveyId(survey.getId());
        //查询一个问卷中的所有问题及选项
        List<Question> questions = questionService.query(question);
        //将问题设置为survey的属性
        survey.setQuestions(questions);


        //总投票人数
        AnswerOpt answerOpt = new AnswerOpt();
        answerOpt.setSurveyId(id);
        List<AnswerOpt> answerOpts = surveyService.querydetail(answerOpt);
        Set<String> set = new HashSet<String>();
        for (AnswerOpt opt : answerOpts) {
            set.add(opt.getVoter());
        }

        for (Question question1 : questions) {
            for (QuestionOpt questionOpt : question1.getOptions()) {
                int num = 0;
                for (AnswerOpt opt : answerOpts) {
                    if(questionOpt.getId() == opt.getOptId()){
                        num++;
                    }
                }
                questionOpt.setNum(num);
            }
        }
        modelMap.addAttribute("survey",survey);
        modelMap.addAttribute("total",set.size());
        return "page/survey/query_detail";
    }


    //任何类型转 String
    public String ObjectString(Object object){
        String num ;
        if (object != null){
            num = object+"";
            return num;
        }else{
            return null;
        }
    }

    //任何类型转Integer
    public Integer ObjectInteger(Object object){
        Integer num ;
        if (object != null){
            num = Integer.parseInt(object+"");
            return num;
        }else{
            return null;
        }
    }
    }





